package com.liarjo.mywebsiteapi.controller.register;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.liarjo.mywebsiteapi.config.AppConfig;
import com.liarjo.mywebsiteapi.config.AppConstants;
import com.liarjo.mywebsiteapi.pojo.User;
import com.liarjo.mywebsiteapi.pojo.UserBaseMapper;

@Service
public class RegisterService {
    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AppConfig appConfig;

    @Transactional(rollbackFor = Exception.class)
    public RegisterResult register(RegisterRequest registerRequest) throws Exception {
        if (registerMapper.existsByUsername(registerRequest.getUserName()) > 0) {
            throw new RuntimeException("用户名已存在");
        }
        // 插入数据库
        User user = new User();
        user.setUserName(registerRequest.getUserName());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        userBaseMapper.insert(user);
        if (registerRequest.getAvatar() != null) {
            // 头像上传
            String avatarFilename = IdWorker.getId() + "." + FilenameUtils.getExtension(registerRequest.getAvatar().getOriginalFilename());
            File avatarTargetFile = new File(appConfig.getUploadDir() + "/" + avatarFilename);
            FileUtils.forceMkdirParent(avatarTargetFile);
            registerRequest.getAvatar().transferTo(avatarTargetFile);
            user.setAvatar(avatarFilename);
        }
        // 设定role
        user.setRole(AppConstants.ROLE_USER);
        userBaseMapper.updateById(user);
        return null;
    }
}
